import type { RouteConfig } from "@/pro-router/types";

export const trimPath = (path: string) => path.trim().replace(/^\//, "").replace(/\/$/, "");

/**
 * 生成检验权限的方法
 * @param permissions
 */
const mkCheckPermission = (permissions: string[]) => {
  const permissionsSet = new Set(
    permissions.map(permissionPath => trimPath(permissionPath))
  );

  return (path: string) => permissionsSet.has(trimPath(path))
}

export const filterPermission = (appRoutes: RouteConfig[], permissions: string[]) => {
  if (!permissions) return appRoutes;
  const checkPermission = mkCheckPermission(permissions);
  const filterRoute = (appRoutes: RouteConfig[], newRoutes: RouteConfig[]) => {
    (appRoutes || []).map(item => {
      const { path } = item;
      if (checkPermission(path)) {
        newRoutes.push(item)

        const newRoutesChildren: RouteConfig[] = []
        filterRoute(item.children, newRoutesChildren);
        item.children = newRoutesChildren
      }
    })
  }

  const newRoutes: RouteConfig[] = []
  filterRoute(appRoutes, newRoutes)

  return newRoutes;
}
